package personal.study.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import personal.study.form.UserTaskForm;

public class DBUserTask {
	private static Log log = LogFactory.getLog(DBUserTask.class);

	public boolean insert(Connection con, UserTaskForm userTaskForm) throws Exception{
		boolean result = false;
		StringBuffer buffer = new StringBuffer(100);
		buffer.append("INSERT INTO UserTask(");
		buffer.append("UserCode,");
		buffer.append("TaskCode,");
		buffer.append("TaskName,");
		buffer.append("Flag,");
		buffer.append("Remark) ");
		
		if(log.isDebugEnabled()){
			
		}
		
		buffer.append("VALUES(?,?,?,?,?)");
		PreparedStatement ps = null;
		try{
			ps = con.prepareStatement(buffer.toString());
			ps.setString(1, userTaskForm.getUserCode());
			ps.setString(2, userTaskForm.getTaskCode());
			ps.setString(3, userTaskForm.getTaskName());
			ps.setString(4, userTaskForm.getFlag());
			ps.setString(5, userTaskForm.getRemark());
			ps.executeUpdate();
			result = true;
		}catch(Exception e){
			log.error(e.getMessage());
		}finally{
			ps.close();
		}
		return result;
	}
	
	public boolean delete(Connection con, String conditions) throws Exception{
		boolean result = false;
		StringBuffer buffer = new StringBuffer(100);
		buffer.append("DELETE FROM UserTask WHERE ");
		buffer.append(conditions);
		
		PreparedStatement ps = null;
		try{
			ps = con.prepareStatement(buffer.toString());
			ps.executeUpdate();
			result = true;
		}catch(Exception e){
			log.error(e.getMessage());
		}finally{
			ps.close();
		}
		return result;
	}
	
	public Collection<UserTaskForm> findByConditions(Connection con, String conditions) throws Exception{
		Collection<UserTaskForm> col = new ArrayList<UserTaskForm>();
		StringBuffer buffer = new StringBuffer(200);
		buffer.append("SELECT ");
		buffer.append("UserCode,");
		buffer.append("TaskCode,");
		buffer.append("TaskName,");
		buffer.append("Flag,");
		buffer.append("Remark ");
		buffer.append("FROM UserTask WHERE ");
		buffer.append(conditions);
		
		PreparedStatement ps = null;
		ResultSet rs = null;
		UserTaskForm userTaskForm = null;
		try{
			ps = con.prepareStatement(buffer.toString());
			rs = ps.executeQuery();
			while(rs.next()){
				userTaskForm = new UserTaskForm();
				userTaskForm.setUserCode(rs.getString("UserCode"));
				userTaskForm.setTaskCode(rs.getString("TaskCode"));
				userTaskForm.setTaskName(rs.getString("TaskName"));
				userTaskForm.setFlag(rs.getString("Flag"));
				userTaskForm.setRemark(rs.getString("Remark"));
				col.add(userTaskForm);
			}
		}catch(Exception e){
			log.error(e.getMessage());
		}finally{
			ps.close();
			rs.close();
		}
		return col;
	}
}
